package com.mdc.mansion.core.modules.restaurant.impl;

import com.esotericsoftware.minlog.Log;
import com.google.common.collect.Lists;
import com.mdc.mansion.common.exception.BusinessException;
import com.mdc.mansion.common.util.I18nUtil;
import com.mdc.mansion.core.common.restaurant.RestaurantCommon;
import com.mdc.mansion.core.common.translate.TranslateLanguage;
import com.mdc.mansion.core.common.translate.TranslateService;
import com.mdc.mansion.core.common.util.RestaurantSupport;
import com.mdc.mansion.core.modules.basedata.QrcodeUseLogService;
import com.mdc.mansion.core.modules.order.RestaurantOrderComboItemService;
import com.mdc.mansion.core.modules.order.RestaurantOrderItemService;
import com.mdc.mansion.core.modules.order.RestaurantOrderService;
import com.mdc.mansion.core.modules.restaurant.RestaurantTableService;
import com.mdc.mansion.core.modules.restaurant.dto.RestaurantTableDTO;
import com.mdc.mansion.dataaccess.common.context.ContextHolder;
import com.mdc.mansion.dataaccess.common.persistence.Page;
import com.mdc.mansion.dataaccess.common.service.CrudService;
import com.mdc.mansion.dataaccess.modules.basedata.entity.QrcodeUseLog;
import com.mdc.mansion.dataaccess.modules.order.entity.RestaurantOrder;
import com.mdc.mansion.dataaccess.modules.order.entity.RestaurantOrderComboItem;
import com.mdc.mansion.dataaccess.modules.order.entity.RestaurantOrderItem;
import com.mdc.mansion.dataaccess.modules.restaurant.dao.RestaurantTableDao;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.Restaurant;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.RestaurantTable;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.mo.RestaurantTableMO;

import org.springframework.beans.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;

/**
 * 餐厅餐桌信息ServiceImpl
 * @author mingdongc
 * @version 2018-01-01
 */
@Service
public class RestaurantTableServiceImpl extends CrudService<RestaurantTableDao, RestaurantTable> implements RestaurantTableService,ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private TranslateService translateService;
    @Autowired
    private RestaurantOrderComboItemService restaurantOrderComboItemService;
    @Autowired
    private RestaurantOrderItemService restaurantOrderItemService;
  
    
    private RestaurantOrderService restaurantOrderService;
    
    @Autowired
    private QrcodeUseLogService qrcodeUseLogService;
    
    /**(non-Javadoc)
    * @param restaurantId
    * @return
    * @see com.mdc.mansion.core.modules.restaurant.RestaurantTableService#selectRestaurantTableWithStatus(java.lang.String,java.lang.String)
    */
    @Override
    public List<RestaurantTableMO> selectRestaurantTableWithStatus(String restaurantId,String restaurantTableId) {
    	String tableStatus = "0";
    	List<RestaurantTableMO> tableinfoList = Lists.newArrayList();
    	RestaurantTableMO restaurantTableMO = null;
    	RestaurantTable table  = new RestaurantTable();
    	table.setRestaurantId(restaurantId);
    	if(StringUtils.isNoneBlank(restaurantTableId))
    	{
    		table.setId(restaurantTableId);
    	}
    	List<RestaurantTable> tableList = this.findList(table);
    	if( null ==  tableList || 0 == tableList.size() )
    	{
    		return null;
    	}
    	
    	for(RestaurantTable restaurantTable : tableList)
    	{
    		RestaurantOrder restaurantOrder = new RestaurantOrder();
    	    restaurantOrder.setPage(new Page<RestaurantOrder>(-1));
    	    restaurantOrder.setRestaurantTableId(restaurantTable.getId());
    	    restaurantOrder.setDelFlag("0");
    	    Page<RestaurantOrder> page = new Page<>(-1);
    	    page.setOrderBy("create_time desc");
    	    restaurantOrder.setPage(page);
    	    List<RestaurantOrder> tableOrderList = restaurantOrderService.findList(restaurantOrder);
    	    if(tableOrderList!=null &&tableOrderList.size()>0){
    	    	RestaurantOrder tableOrder = tableOrderList.get(0);
    	    	int orderStatus = tableOrder.getOrderStatus();
    	    	/****用户点餐未确认***/
    	    	if(RestaurantCommon.RestaurantOrderStatusStep0 == orderStatus )
    	    	{
    	    		tableStatus = "1";
    	    	}else if(RestaurantCommon.RestaurantOrderStatusStep1 == orderStatus)////订单已确认,但是可能存在未确认的菜品
    	    	{
    	    		tableStatus = "2";
    	    		RestaurantOrderItem item = new RestaurantOrderItem();
    	    		item.setRestaurantId(tableOrder.getRestaurantId());
    	    		item.setRestaurantOrderId(tableOrder.getId());
    	    		item.setDishesStatus(RestaurantCommon.RestaurantOrderDishesStatusStep0);
    	    		List<RestaurantOrderItem> itemList= restaurantOrderItemService.findList(item);
    	    		if(null != itemList && 0 < itemList.size())
    	    		{
    	    			tableStatus = "1";
    	    		}
    	    	}else////剩余状态为已结账或撤单,均为餐桌空闲状态
    	    	{
    	    		tableStatus = "0";
    	    	}
    	    }else
    	    {
    	    	tableStatus = "0";
    	    }
    	    restaurantTableMO = new RestaurantTableMO();
    	    BeanUtils.copyProperties(restaurantTable, restaurantTableMO);
    	    restaurantTableMO.setStatus(tableStatus);
    	    tableinfoList.add(restaurantTableMO);
    	}
    	
    	return tableinfoList;
    	
//    	List<RestaurantTableMO> tableinfoList = this.dao.selectRestaurantTableWithStatus(restaurantId, restaurantTableId);
//    	// 餐桌状态业务处理
//    	if(restaurantTableId!=null && !"".equals(restaurantTableId) &&tableinfoList!=null && tableinfoList.size()>0 ){
//    	    RestaurantOrder restaurantOrder = new RestaurantOrder();
//    	    restaurantOrder.setPage(new Page<RestaurantOrder>(-1));
//    	    restaurantOrder.setRestaurantTableId(restaurantTableId);
//    	    restaurantOrder.setDelFlag("0");
//    	    Page<RestaurantOrder> page = new Page<>(-1);
//    	    page.setOrderBy("create_time desc");
//    	    restaurantOrder.setPage(page);
//    	    List<RestaurantOrder> tableOrderList = restaurantOrderService.findList(restaurantOrder);
//    	    if(tableOrderList!=null &&tableOrderList.size()>0){
//    	        RestaurantOrder tableOrder = tableOrderList.get(0);
//    	        int orderStatus = tableOrder.getOrderStatus();
//    	        String tableOrderID = tableOrder.getId();// 餐桌订单ID 
//    	        // 查询 订单的菜品状态
//    	        if(orderStatus == 1){// 只有订单状态为1 服务员确认
//    	            boolean dishesWaitCheck = this.orderDishesWaitCheck(tableOrderID, restaurantTableId);
//    	            if(!dishesWaitCheck){ // 没有待确认的 那么设置餐桌状态为2
//    	                for(RestaurantTableMO restaurantTableMO : tableinfoList){
//    	                    restaurantTableMO.setStatus("2");
//    	                }
//    	            }
//    	        }
//    	    }
//    	}
//        return tableinfoList;
    }
    @Transactional
	@Override
    public void saveOrUpdate(RestaurantTableDTO restaurantTableDTO) {
	    String id = restaurantTableDTO.getId();
	    String restaurantId = ContextHolder.currentRestaurantId();
	    restaurantTableDTO.setRestaurantId(restaurantId);
	    String language = restaurantTableDTO.getLanguage();
	    // 调用翻译接口进行翻译  设置对应的name为对应语言的名字
	    RestaurantTable paramRestaurantTable = new RestaurantTable();
	    String name = restaurantTableDTO.getName();
	    if(language!=null&&!"".equals(language)){
            String chinaName = translateService.translate(name, TranslateLanguage.CHINA);
            String englishName = translateService.translate(name, TranslateLanguage.ENGLISH);
            String indonesiaName = translateService.translate(name, TranslateLanguage.INDONESIA);
            restaurantTableDTO.setName(indonesiaName);
            restaurantTableDTO.setChineseName(chinaName);
            restaurantTableDTO.setEnglishName(englishName);
        }
	    
	    
	    /***判断该二维码是否已经被其他餐桌使用***/
	    paramRestaurantTable.setQrCodeSign(restaurantTableDTO.getQrCodeSign());
	    List<RestaurantTable> tableQrList =  this.dao.findList(paramRestaurantTable);
	    if(CollectionUtils.isNotEmpty(tableQrList) && (!restaurantTableDTO.getQrCodeSign().equals(tableQrList.get(0).getQrCodeSign())))
	    {
	    	Log.error("XXXXXXXXXX===================>: 该二维码已经被其他餐桌使用");
	    	throw new BusinessException(I18nUtil.getMessage("qr.code.sign.exists"));
	    }
	    
	    
	    paramRestaurantTable = new RestaurantTable();
	    if(id==null ||"".equals(id)){// 新增
	        // 验证二维码是否已经被绑定了
	        paramRestaurantTable.setQrCodeSign(restaurantTableDTO.getQrCodeSign());
	        List<RestaurantTable> existsList = this.dao.selectByParam(paramRestaurantTable);
	        if(existsList!=null && existsList.size() >0){
	            throw new BusinessException(I18nUtil.getMessage("qr.code.sign.exists"));
	        }
	        this.save(restaurantTableDTO);
	    }else{// 编辑
	        // 验证餐桌是否存在
	        paramRestaurantTable.setId(id);
	        List<RestaurantTable> existsIds = this.dao.selectByParam(paramRestaurantTable);
            if(existsIds==null || existsIds.size() ==0){
                throw new BusinessException(I18nUtil.getMessage("restaurant.table.does.not.exist")); // 餐桌不存在
            }
            // 验证二维码是否被其它餐桌使用
            paramRestaurantTable.setId("");
            paramRestaurantTable.setQrCodeSign(restaurantTableDTO.getQrCodeSign());
            List<RestaurantTable>  existsCodes =  this.dao.selectByParam(paramRestaurantTable);
            if(existsCodes!=null&&existsCodes.size()>1){
                throw new BusinessException(I18nUtil.getMessage("qr.code.sign.exists"));
            }
            if(existsCodes!=null&&existsCodes.size()==1){
                if(!existsCodes.get(0).getId().equals(id)){
                    throw new BusinessException(I18nUtil.getMessage("qr.code.sign.exists"));
                }
            }
	        this.updateSelective(restaurantTableDTO);
	    }
	    
	    
	    
	    /****对于二维码绑定需要增加处理过程,需要判断是否是批量生成的二维码,如果是需要更新批量生成表*****/
	    /****需要对餐桌ID进行处理,如果餐桌ID已经绑定二维码了,则将现在的二维码状态作废,再更新餐厅ID,餐桌ID到新的二维码上,并修改新的二维码状态为已用***/
	    	QrcodeUseLog qrcodeUseLog = new QrcodeUseLog();
		    qrcodeUseLog.setRestaurantTableId(id);
		    qrcodeUseLog.setQrcodeStatus(QrcodeUseLog.QRCODE_STATUS.USED.getVal());
		    List<QrcodeUseLog> qrCodeList = qrcodeUseLogService.findList(qrcodeUseLog);
		    
		    if( CollectionUtils.isNotEmpty(qrCodeList))
		    {
		    	QrcodeUseLog useLog = qrCodeList.get(0);
		    	qrcodeUseLog =  new QrcodeUseLog();
		    	qrcodeUseLog.setId(useLog.getId());
		    	qrcodeUseLog.setQrcodeStatus(QrcodeUseLog.QRCODE_STATUS.INVALID.getVal());
		    	qrcodeUseLog.setUpdateBy(RestaurantSupport.getCurrentOperationUser());
		    	qrcodeUseLog.setUpdateTime(Calendar.getInstance().getTime());
		    	qrcodeUseLogService.updateSelective(qrcodeUseLog);
		    }
		    
		    qrcodeUseLog = new QrcodeUseLog();
		    qrcodeUseLog.setCodeSign(restaurantTableDTO.getQrCodeSign());
		    qrcodeUseLog.setQrcodeStatus(QrcodeUseLog.QRCODE_STATUS.UNUSED.getVal());
		    qrCodeList = qrcodeUseLogService.findList(qrcodeUseLog);
		    if( CollectionUtils.isNotEmpty(qrCodeList))
		    {
		    	QrcodeUseLog useLog = qrCodeList.get(0);
		    	qrcodeUseLog =  new QrcodeUseLog();
		    	qrcodeUseLog.setId(useLog.getId());
		    	qrcodeUseLog.setQrcodeStatus(QrcodeUseLog.QRCODE_STATUS.USED.getVal());
		    	qrcodeUseLog.setRestaurantId(restaurantId);
		    	qrcodeUseLog.setRestaurantTableId(id);
		    	qrcodeUseLog.setUpdateBy(RestaurantSupport.getCurrentOperationUser());
		    	qrcodeUseLog.setUpdateTime(Calendar.getInstance().getTime());
		    	qrcodeUseLogService.updateSelective(qrcodeUseLog);
		    }
		    
    }

    /**
     * 2018年1月7日 13:29:01 xizf
     * 查询餐厅空闲的餐桌列表
     */
    @Override
    public List<RestaurantTable> getFreeRestaurantTable(Restaurant restaurant)throws Exception {

        RestaurantTable restaurantTable = null;
        List<RestaurantTable>   tableList = null;
        restaurantTable = new RestaurantTable();
        
        restaurantTable.setRestaurantId(restaurant.getId());
        tableList = this.dao.getFreeTableList(restaurantTable);
        if(!( null == tableList || 0 ==tableList.size()))
        {
            return tableList;
        }else
        {
        	return null;
        }
        
    }
    /**
     * 订单菜品是否存在待确认状态的菜品  
     * 1、先判断菜品订单是否存在
     * 2、再判断套餐订单是否存在待确认的状态
     * @date create_time：2018年2月5日 下午11:16:43
     * @return
     */
    private boolean orderDishesWaitCheck(String restaurantOrderId,String restaurantTableId){
        boolean waitCheck = false;
        RestaurantOrderItem restaurantOrderItem = new RestaurantOrderItem();
        restaurantOrderItem.setRestaurantId(ContextHolder.currentRestaurantId());
        restaurantOrderItem.setRestaurantOrderId(restaurantOrderId);
        restaurantOrderItem.setRestaurantTableId(restaurantTableId);
        Page<RestaurantOrderItem> page = new Page<RestaurantOrderItem>(-1);
        restaurantOrderItem.setPage(page);
        List<RestaurantOrderItem> orderItemList = restaurantOrderItemService.findList(restaurantOrderItem);
        if(orderItemList!=null&& orderItemList.size()>0){
            for(RestaurantOrderItem orderItem : orderItemList){
                if(orderItem.getDishesStatus() == 0){// 存在待确认的 那么直接返回true
                    waitCheck = true;
                    return waitCheck;
                }
                
            }
        }
        // 验证套餐菜品是否存在待确认
        RestaurantOrderComboItem restaurantOrderComboItem = new RestaurantOrderComboItem();
        restaurantOrderComboItem.setRestaurantId(ContextHolder.currentRestaurantId());
        restaurantOrderComboItem.setRestaurantOrderId(restaurantOrderId);
        restaurantOrderComboItem.setRestaurantTableId(restaurantTableId);
        Page<RestaurantOrderComboItem> page2 = new Page<RestaurantOrderComboItem>(-1);
        restaurantOrderComboItem.setPage(page2);
        List<RestaurantOrderComboItem> comboItemList = restaurantOrderComboItemService.findList(restaurantOrderComboItem);
        if(comboItemList!=null&& comboItemList.size()>0){
            for(RestaurantOrderComboItem comboItem : comboItemList){
                if(comboItem.getDishesStatus() == 0){// 存在待确认的 那么直接返回true
                    waitCheck = true;
                    return waitCheck;
                }
            }
        }
        return waitCheck;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext=event.getApplicationContext();
        if (applicationContext.getParent() == null) {
            restaurantOrderService = applicationContext.getBean(RestaurantOrderService.class);
        }
    }
}